package main

import (
	"net/http"
)

type Server interface {
	Routable
	Start(address string) error
}

// sdkHttpServer 这个是基于 net/http 这个包实现的 http server
type sdkHttpServer struct {
	Name    string
	handler Handler
	root    Filter
}

func (s *sdkHttpServer) Route(method string, pattern string, handleFunc func(ctx *Context)) {
	//key := s.handler.key(method, pattern)
	//s.handler.handlers[key] = handleFunc
	s.handler.Route(method, pattern, handleFunc)

}

func (s *sdkHttpServer) Start(address string) error {
	//handler := &HandlerBasedMap{}
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		c := NewContext(w, r)
		s.root(c)
	})
	return http.ListenAndServe(address, nil)
}

func NewHttpServer(name string, builders ...FilterBuilder) Server {
	handler := NewHandlerBasedOnMap()
	var root Filter = func(ctx *Context) {
		handler.ServeHTTP(ctx.W, ctx.R)
	}
	for i := len(builders) - 1; i >= 0; i-- {
		b := builders[i]
		root = b(root)
	}
	return &sdkHttpServer{
		Name:    name,
		handler: NewHandlerBasedOnMap(),
		root:    root,
	}
}
